<?php

namespace app\admin\model\spell;

use fast\Utils;
use think\Exception;
use think\Model;


class Refund extends Model
{





    // 表名
    protected $name = 'refund_list';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [

    ];

    static protected $rules=[
        ['datetime'=>'小于24小时','rate'=>'0','sec'=>3600*24,'lt'=>0],
        ['datetime'=>'24小时-5天','rate'=>'0.9','sec'=>5*86400,'lt'=>3600*24],
        ['datetime'=>'5天-10天','rate'=>'1.01','sec'=>10*86400,'lt'=>5*86400],
        ['datetime'=>'10天-20天','rate'=>'1.03','sec'=>20*86400,'lt'=>10*86400],
        ['datetime'=>'20天-30天','rate'=>'1.07','sec'=>30*86400,'lt'=>20*86400],
        ['datetime'=>'大于30天','rate'=>'1.12','sec'=>-1,'lt'=>30*86400],
    ];


    public function __construct($data = [])
    {
        parent::__construct($data);
    }

    /**
     * 退款取消
     */
    public static function returnOrder($order,$return = 100)
    {
        $data = array(
            "uid"=>$order['uid'],
            "orderId"=>$order["orderId"],
            "refundId"=>"refund".time(),
            "payPrice"=>$order["payPrice"],
            "returnPrice"=>$return,
            "payType"=>$order["payType"],
            "transaction_id"=>$order["transaction_id"],
            "status"=>1,
            "createtime"=>time(),
            "updatetime"=>time(),
        );
        $newId = self::insert($data,false,1);
        $refundId = \fast\Utils::getOrderId("refund",$newId);
        //if($data["payType"] == "credit"){
            \app\common\model\User::money($order['uid'], $data['returnPrice'], 10, "取消订单退款",$refundId);
            $msg = "余额退款成功";
        /*}elseif($data['payType'] == 'wechat'){
            $wechatpay = new \app\common\library\Wechatpay();
            $result = $wechatpay->refund([
                "orderId"=>$refundId,
                "transaction_id"=>$data["transaction_id"],
                "payPrice"=>$data["payPrice"],
                "returnPrice"=>$data["returnPrice"],
            ]);
            if($result['result_code'] != "SUCCESS" || $result['return_code'] != "SUCCESS"){
                throw new \Exception("退款失败".$result['err_code_des']);
            }
            $msg = $result['refund_id'];
        }elseif($data['payType'] == "alipay"){
            $alipay = new \app\common\library\Aop();
            $result = $alipay->refund([
                "out_trade_no"=>$data['orderId'],
                'trade_no'=>$data['transaction_id'],
                'refund_amount'=>$data['returnPrice'],
                'refund_reason'=>'正常退款',
                'out_request_no' => $refundId,
            ]);
            $msg = $result['msg'];
        }*/
        self::where('id',$newId)->update([
            "refundId"=>$refundId,
            "status"=>2,
            "remark"=>$msg,
            "updatetime"=>time(),
        ]);
    }
    /**
     * 取消是否满足
     */
    public static function cancelInfo($orderInfo)
    {
        $return = 100;
        if($orderInfo['model'] == 2) {
            $day = \think\config::get("site.pingorderreturnday");
            $time = time() - $day * 24 * 3600;
            if ($orderInfo['payTime'] > $time) {
                return 0;
            }
            $spellInfo = \app\admin\model\spell\Spell::where('ptid',$orderInfo['id'])->where('start',1)->find();
            $robotPrice = \app\admin\model\spell\Spell::where('ptid',$orderInfo['id'])->where('start',0)->where('robot',1)->sum("price");
            $countPrice = \app\admin\model\spell\Spell::where('ptid',$orderInfo['id'])->where('start',0)->where('robot',0)->sum("price");
            $countPercent = \think\config::get("site.pingorderreturnspellprice");
            $returnFailPercent = \think\config::get("site.pingorderreturnpercent");
            $percent = $spellInfo?bcmul(sprintf("%.2f",$countPrice/($spellInfo['totalPrice']-$robotPrice)),100):100;
            return $percent>=$countPercent?$return:$returnFailPercent;
        }
        return $return;
    }

    public static function getRules($orderInfo){
        $rules=self::$rules;
        foreach ($rules as $key=>&$rule){
            $rule['amount']=bcmul($orderInfo['payPrice'],$rule['rate'],2);
            $diff=$rule['lt']-(time()-$orderInfo['createtime']);
            $rule['remaining']=Utils::vtime($diff) ?: '0小时';
        }
        $result=[
            'returnAmount'=>self::getReturnAmount($orderInfo)[0],
            'rate'=>self::getReturnAmount($orderInfo)[1],
            'orderPrice'=>$orderInfo['payPrice'],
            'datetime'=>Utils::vtime(time()-$orderInfo['createtime']),
            'rules' =>$rules,
        ];
        return $result;
    }

    public static function getReturnAmount($orderInfo){
        $last=0;
        foreach (self::$rules as $key=>&$rule){
            $diff=time()-$orderInfo['createtime'];
            if($diff<=$rule['sec'] && $diff>$last){
                $arr[]=bcmul($orderInfo['payPrice'],$rule['rate'],2);
                $arr[]=$rule['rate'];
                return $arr;
            }elseif($rule['sec']==-1){
                $arr[]=bcmul($orderInfo['payPrice'],1.12,2);
                $arr[]=1.12;
                return $arr;
            }
            $last=$rule['sec'];
        }
        return [];

    }



}
